﻿package tv.colmeia.game.comm {
		/**
	* ...
	* @author Martin Fabichak @ colmeia.tv
	*/
	
	import flash.errors.*;
	import flash.events.*;
	import flash.net.Socket;
	import tv.colmeia.game.assets.events.GameSocketEvent;

	public class GameSocket extends Socket {
		private var response:String;
		private var player1:String;
		private var player2:String;
		
		public function GameSocket(host:String = null, port:uint = 0) {
			super(host, port);
			configureListeners();
		}

		private function configureListeners():void {
			addEventListener(Event.CLOSE, closeHandler);
			addEventListener(Event.CONNECT, connectHandler);
			addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
			addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
			addEventListener(ProgressEvent.SOCKET_DATA, socketDataHandler);
		}

		private function sendRequest():void {
			trace("sendRequest");
			response = "";
			flush();
		}

		private function readResponse():void {
			trace( "bytesAvailable : " + bytesAvailable );
			var str:* = readUTFBytes(bytesAvailable);
			//var str2:* = readUTF();
			
			//trace( "readUTF() : " + readUTF() );
			
			/*trace( "bytesAvailable : " + bytesAvailable );
			trace( "readInt(bytesAvailable) : " + readInt() );
			trace( "readbyte(bytesAvailable) : " + readByte() );
			trace( "readfloat(bytesAvailable) : " + readFloat() );
			//trace( "readbytes(bytesAvailable) : " + readBytes(bytesAvailable) );*/
			trace("STRING RECEBIDA:   " + str);
		//	trace("STRING RECEBIDA2:   " + str2);
			
			var mac:String = str.substring(0, 16);
			var botao:int = str.substring(18, 1) as int;
			
			if (!player1) {
				player1 = mac;
			}else if (!player2) {
				player2 = mac;
			}
			
			if (mac == player1) {
				if (botao == 4)	dispatchEvent(new GameSocketEvent(GameSocketEvent.GAME_EVENT, 65));
				if (botao == 6)	dispatchEvent(new GameSocketEvent(GameSocketEvent.GAME_EVENT, 68));
				
			}
			if (mac == player2) {
				if (botao == 4)	dispatchEvent(new GameSocketEvent(GameSocketEvent.GAME_EVENT, 37));
				if (botao == 6)	dispatchEvent(new GameSocketEvent(GameSocketEvent.GAME_EVENT, 39));
			}
		}

		private function closeHandler(event:Event):void {
			trace("closeHandler: " + event.type);
		}

		private function connectHandler(event:Event):void {
			trace("connectHandler: " + event.type);
			//sendRequest();
		}

		private function ioErrorHandler(event:IOErrorEvent):void {
			trace("ioErrorHandler: " + event);
		}

		private function securityErrorHandler(event:SecurityErrorEvent):void {
			trace("securityErrorHandler: " + event);
		}

		private function socketDataHandler(event:ProgressEvent):void {
			/*trace("socketDataHandler: " + event.bytesTotal +  "  "+ event.toString() );*/
			readResponse();
		}
	}
	
}